<template>
  <jke-modal
    :visible.sync="jkeForm.visible"
    :width="1200"
    :title="jkeForm.title"
    :fullscreen.sync="jkeForm.fullscreen"
    :switchFullscreen="jkeForm.switchFullscreen"
  >
    <div class="page-scroll-wrap">
      <div class="uni-card">
        <div class="bd-line"></div>
        <div class="item-wrap1">
          <div class="detail-item" style="width: 33%">
            <p class="subtitle">出库单编号</p>
            <p class="secondary-text">{{ detailInfo.entryCode || '-' }}</p>
          </div>
          <div class="detail-item" style="width: 33%">
            <p class="subtitle">出库单类型</p>
            <p class="secondary-text">
              {{ detailInfo.outWarehouseTypeName || '-' }}
            </p>
          </div>
          <div class="detail-item" style="width: 33%">
            <p class="subtitle">领出人</p>
            <p class="secondary-text">{{ detailInfo.receiverPersionName || '-' }}</p>
          </div>
        </div>
        <div class="item-wrap">
          <div class="detail-item" style="width: 33%">
            <p class="subtitle">出库时间</p>
            <p class="secondary-text">{{ detailInfo.outWarehouseTime || '-' }}</p>
          </div>
          <div class="detail-item" style="width: 33%">
            <p class="subtitle">销售订单</p>
            <p class="secondary-text">
              {{ detailInfo.saleOrderCode || '-' }}
            </p>
          </div>
          <div class="detail-item" style="width: 33%"></div>
        </div>
      </div>

      <div style="flex: 1; background: #fff; margin-bottom: 12px; margin-top: 12px">
        <a-tabs v-model="cuttentTab" @change="tabChange">
          <a-tab-pane key="1" tab="出库物品明细">
            <div>
              <a-card :bordered="false">
                <a-col :span="24">
                  <a-table
                    :columns="processTable.columns"
                    :dataSource="processTable.dataSource"
                    :scroll="{ x: computedX }"
                  >
                    <span slot="customIndex" slot-scope="text, record, index">
                      {{ (getGoodsListPage.current - 1) * getGoodsListPage.pageSize + index + 1 }}
                    </span>
                  </a-table>
                </a-col>
              </a-card>
            </div>
          </a-tab-pane>
          <a-tab-pane key="2" tab="自定义信息">
            <div>
              <a-card :bordered="false">
                <div class="uni-card">
                  <div class="item-wrap1" v-if='formTypeExtendedFields.length'>
                    <div
                      class="detail-item"
                      style="width: 33%"
                      v-for="(item, index) in formTypeExtendedFields"
                      :key="index"
                    >
                      <p class="subtitle">{{ item.fieldName }}</p>
                      <p class="secondary-text">{{ detailInfo.extDataJson[item.fieldKey] || '-' }}</p>
                    </div>
                    <div
                      class="detail-item"
                      style="width: 33%"
                      v-for="(item, index) in formTypeExtendedFields.length % 3"
                      :key="index"
                    ></div>
                  </div>
                  <div v-else>
                    暂无数据
                  </div>
                </div>
              </a-card>
            </div>
          </a-tab-pane>
        </a-tabs>
      </div>
    </div>
    <Examine v-if="detailInfo.flowInstId" type="2" :id="detailInfo.flowInstId" ref="examine" />
  </jke-modal>
</template>
<script>
import { FormTypes } from '@/utils/JEditableTableUtil'
import crumbs from '@/components/crumbs.vue'
import { getFileListByIds } from '@/api/api'
import FileDetail from '@/components/fileActions/FileDetail'
import { returnMaterialQueryById } from '@/api/goodsManagement'
import { API } from '@/api/requestFzs'
import { numFormat } from '@/utils/util'
import LogoVue from '../../../components/tools/Logo.vue'
import { apiBaseUrlDownload } from '@/utils/request'
import FlowStatus from '@/pubComponent/FlowStatus'
import { APILX } from '@/api/requestLx'
import Examine from '@/components/examine'
import { goodsColumns } from './detailColumn.js'

const goodsPagination = {
  current: 1,
  total: 0,
  pageSize: 10,
  pageSizeOptions: ['10', '20', '30', '40', '50'],
}
export default {
  data() {
    return {
      jkeForm: {
        title: '出库单详情',
        visible: false,
        fullscreen: true,
        switchFullscreen: true,
      },
      cuttentTab: '1',

      domianURL: apiBaseUrlDownload, //表格图片展示
      isLoading: false, //防止tab来回切换 导致数据重复渲染
      tabAll: '全部',
      tabAbNormal: '盘点异常库存（0）',
      tabNormal: '盘点正常库存（0）',
      getGoodsListPage: Object.assign({}, goodsPagination),
      pagination1: Object.assign({}, goodsPagination),
      pagination2: Object.assign({}, goodsPagination),
      pagination3: Object.assign({}, goodsPagination),
      tabStatus: '',
      queryTd: '',
      refKeys: ['processTable'],
      formTypeExtendedFields: [],
      processTable: {
        loading: false,
        dataSource: [],
        columns: [],
      },
      numFormat,
      detailInfo: {},
    }
  },
  components: {
    crumbs,
    FileDetail,
    Examine,
    FlowStatus,
  },
  computed: {
    computedX() {
      let num = 0
      for (let item of this.processTable.columns) {
        num += Number(item.width)
      }
      return num
    },
  },
  methods: {
    tabChange(activeKey) {
      console.log('当前tab选中的tabKey：', activeKey)
    },
    handleAlready(props) {
      let tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      let that = this
      that.$antdConfirm({
        title: '确定要标记为已处理吗?',
        content: `建议新建出库单或出库单后再标记为 "已处理".`,
        onOk() {
          APILX.wmsWarehouseInventoryUpdateException(tableValue.id).then((res) => {
            if (res.code == 200) {
              that.$antdMessage.success('已标记为已处理！')
              that.getTable()
            } else {
              that.$antdMessage.error(res.message)
            }
          })
        },
        onCancel() {},
      })
    },
    clickOut() {
      let outObj = {
        fromPage: 'stockCheckDetail',
        id: this.queryTd,
      }
      this.$openWay(this, true, '/buildOutStock', outObj)
    },
    clickIn() {
      let inObj = {
        fromPage: 'stockCheckDetail',
        id: this.queryTd,
      }
      this.$openWay(this, true, '/buildInStock', inObj)
    },
    checkStatus(props) {
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (tableValue.status == 'abnormal' && tableValue.handleStatus == '0') {
        return true
      }
      return false
    },
    getAbNormal() {
      this.getTableNum('abnormal')
    },
    getNormal() {
      this.getTableNum('normal')
    },
    // 分页
    onChangePage(current, pageSize, key) {
      console.log('current, pageSize', current, pageSize)
      this[key].current = current
      this.getGoodsListPage.current = current
      this.getTable()
    },
    onShowSizeChange(current, pageSize, key) {
      console.log('current, pageSize', this.tabStatus)
      this[key].pageSize = pageSize
      this[key].current = current
      this.getGoodsListPage.pageSize = pageSize
      this.getGoodsListPage.current = current
      this.getTable()
    },
    // tab分页
    changeCurrent(key) {
      if (key == '0') {
        this.tabStatus = ''
        this.columns[this.columns.length - 1].type = FormTypes.slot
        this.goodsTable.columns = JSON.parse(JSON.stringify(this.columns))
        console.log('this.pagination1:', this.pagination1)
        this.getGoodsListPage = this.pagination1
      } else if (key == '1') {
        this.tabStatus = 'abnormal'
        this.columns[this.columns.length - 1].type = FormTypes.slot
        this.goodsTable.columns = JSON.parse(JSON.stringify(this.columns))
        console.log('this.pagination2:', this.pagination2)
        this.getGoodsListPage = this.pagination2
      } else if (key == '2') {
        this.tabStatus = 'normal'
        this.columns[this.columns.length - 1].type = FormTypes.hidden
        let newArr = JSON.parse(JSON.stringify(this.columns))
        this.goodsTable.columns = newArr.filter((item) => {
          return item.title != '操作'
        })
        console.log('this.pagination3:', this.pagination3)
        this.getGoodsListPage = this.pagination3
      }
      this.getTable()
    },
    setColor(s) {
      let cor = {
        1: '#888888', //黑色
        盘点中: '#1890FF', //蓝色
        盘点正常: '#00B042', //绿色
        盘点异常: '#ff4d4f', //红色
      }
      return cor[s] || ''
    },
    /* 面包屑返回 */
    goBack() {
      this.jkeForm.visible = false
    },
    initDetail(id) {
      this.jkeForm.visible = true
      this.tabStatus = ''
      this.queryTd = id
      // this.getNormal()
      // this.getAbNormal()
      // this.getTable()
      APILX.warehouseOutboundOrderInfoQueryById({ id: this.queryTd }).then((res) => {
        if (res.code == 200) {
          this.detailInfo = res.result
        } else {
          this.$antdMessage.error(res.message)
        }
      })
      APILX.warehouseEntryDetailList({ entryId: this.queryTd, inOutType: 1 }).then((res) => {
        if (res.code == 200) {
          this.detailInfo.detailList = res.result.records
          this.processTable.dataSource = res.result.records.map((ele) => {
            return {
              ...ele,
              ...ele.extDataJson,
            }
          })
        } else {
          this.$antdMessage.error(res.message)
        }
      })
      APILX.formTypeExtendedFieldList({ formType: 5 }).then((res) => {
        if (res.code == 200 && res.result) {
          this.formTypeExtendedFields = res.result
        }
      })
      //出入库明细List
      APILX.formTypeExtendedFieldList({ formType: 6 }).then((res) => {
        if (res.code == 200 && res.result) {
          let formTypeExtendedFields = res.result || []
          let columns = [
            {
              title: '数量',
              key: 'inWarehouseNum',
              dataIndex: 'inWarehouseNum',
              width: 100,
            },
          ]
          formTypeExtendedFields.forEach((field) => {
            columns.push({
              title: field.fieldName,
              dataIndex: field.fieldKey,
              key: field.fieldKey,
              align: 'left',
              width: 200,
              ellipsis: true,
              // slotName: 'processCodeName',
            })
          })

          this.processTable.columns = [...goodsColumns, ...columns]
        }
      })
    },
    getTable() {
      let param = {
        id: this.queryTd,
        status: this.tabStatus,
        pageNo: this.getGoodsListPage.current,
        pageSize: this.getGoodsListPage.pageSize,
      }
      this.goodsTable.dataSource = []
      this.isLoading = true
      APILX.getWmsInventoryGoodsList(param).then((res) => {
        if (res.code == 200) {
          // console.log(res, '进来了没warehouseInventoryUnCompleteList')
          let tableData = res.result.records
          // this.goodsTable.dataSource = []
          tableData.forEach((item) => {
            item.inventoryGoodsScrapNumTextAssistUnit = item.inventoryGoodsScrapNumTextAssistUnit || '-'
            item.inventoryGoodsQualifiedNumTextAssistUnit = item.inventoryGoodsQualifiedNumTextAssistUnit || '-'
            item.goodsQualifiedNumTextAssistUnit = item.goodsQualifiedNumTextAssistUnit || '-'
            item.inventoryResult = item.inventoryResult || '-'
            item.statusText = item.statusText || '-'
            if (item.attachment) {
              let ids = item.attachment
              getFileListByIds({ ids }).then((res) => {
                if (res.code == 200) {
                  let fileList = ''
                  fileList = res.result
                  if (fileList.length > 0) {
                    item.picUrl = this.domianURL + fileList[0].uri
                    this.goodsTable.dataSource.push(item)
                  } else {
                    item.picUrl = require('../../../assets/img/noPicture.jpg')
                    this.goodsTable.dataSource.push(item)
                  }
                }
              })
            } else {
              item.picUrl = require('../../../assets/img/noPicture.jpg')
              this.goodsTable.dataSource.push(item)
            }
            if (item.inventoryGoodsQualifiedNum == '-') {
              item.inventoryGoodsQualifiedNum = 0.0
            }
            if (item.inventoryGoodsScrapNum == '-') {
              item.inventoryGoodsScrapNum = 0.0
            }
          })
          // console.log(this.goodsTable.dataSource, 'this.goodsTable.dataSource')
          if (param.status == 'abnormal') {
            this.tabAbNormal = `盘点异常库存（${res.result.total}）`
            // console.log(this.tabAbNormal, '走 this.tabAbNormal')
          } else if (param.status == 'normal') {
            this.tabNormal = `盘点正常库存（${res.result.total} ）`
            // console.log(this.tabNormal, '走 this.tabNormal', res.result.total)
          }
          this.getGoodsListPage.total = res.result.total
          setTimeout(() => {
            this.isLoading = false
          }, 1000)
        } else {
          this.$antdMessage.error(res.message)
          this.isLoading = false
        }
      })
    },
    getTableNum(status) {
      let param = {
        id: this.queryTd,
        status,
      }
      APILX.getWmsInventoryGoodsList(param).then((res) => {
        if (res.code == 200) {
          if (status == 'abnormal') {
            this.tabAbNormal = `盘点异常库存（${res.result.total}）`
          } else if (status == 'normal') {
            this.tabNormal = `盘点正常库存（${res.result.total} ）`
          }
        } else {
          this.$antdMessage.error(res.message)
        }
      })
    },
    setGoodsScrapNum(props) {
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (tableValue.goodsScrapNum) {
        return tableValue.goodsScrapNum
      } else {
        return ''
      }
    },
    setUnit(props) {
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (tableValue.assistUnit) {
        return tableValue.assistUnit
      } else {
        return ''
      }
    },
    setSpec(props) {
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (tableValue.spec) {
        return tableValue.spec
      } else {
        return '-'
      }
    },
    setName(props) {
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (tableValue.goodsName) {
        return tableValue.goodsName
      } else {
        return ''
      }
    },
    setCode(props) {
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (tableValue.goodsCode) {
        return tableValue.goodsCode
      } else {
        return ''
      }
    },
  },
}
</script>
<style scoped lang="less">
@import '~@/assets/less/public.less';

.itemBox {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;

  img {
    width: 16px;
    height: 16px;
    margin-right: 10px;
  }
}

.item-wrap {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}

.item-wrap1 {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  position: relative;
}

.item-wrap:nth-of-type(n + 2) {
  margin-top: 40px;
}

.detail-item {
  width: 30%;
}

.uni-card {
  padding: 24px 40px;
  margin: -12px 0px 0;
  background: #fff;
}

.bd-line {
  height: 1px;
  background: @greyBorder;
  margin: -12px -40px 24px -40px;
}

.cards-box {
  // height: calc(100vh - 300px);
  // overflow-y: scroll;
  margin-bottom: 20px;
  padding: 0 20px !important;
}

.pic-f {
  display: flex;
  padding: 10px;
  flex: 1;

  .pic-l {
    display: inline-block;
    margin-right: 14px;
  }

  .pic-r {
    flex-direction: column;
    justify-content: space-between;
    display: inline-block;
    font-size: 14px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    color: #444444;
  }
}

.imgClass {
  width: 60px;
  height: 60px;
  border-radius: 6px;
}

.fiexBox {
  position: absolute;
  top: 15px;
  right: -5px;
}

/deep/ .ant-tabs-nav-container {
  margin-top: 0;
  background-color: #fff;
}
/deep/.ant-modal-body {
  height: calc(100vh - 55px) !important;
  .page-scroll-wrap {
    height: calc(100vh - 55px);
    overflow-x: hidden;
    display: flex;
    flex-direction: column;
    overflow-x: hidden;
  }
}
</style>
